package com.yf.controller.api.course;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUser;
import com.yf.entity.UserEntity;
import com.yf.response.R;
import com.yf.service.WxPayService;
import com.yf.service.course.ActivityService;
import com.yf.service.course.SignUpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * User: Administrator
 * Date: 2018-10-26
 * Time: 15:05
 * Description:
 */
@RestController
@RequestMapping("/api/activity")
public class ApiActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private SignUpService signUpService;

    @Autowired
    private WxPayService wxPayService;

    //最新活动
    @GetMapping("/last")
    public R last() {
        return R.ok(activityService.getLast());
    }

    //活动列表
    @GetMapping("/list")
    public R list() {
        return R.ok(activityService.getAll());
    }

    //banner
    @GetMapping("/top")
    public R top() {
        return R.ok(activityService.getBanner());
    }

    //活动详情
    @GetMapping("/info")
    public R info(Long activityId,@LoginUser UserEntity userEntity) {
        return R.ok(activityService.getActivity(userEntity.getId(),activityId));
    }

    //活动报名
    @PostMapping("/signUp")
    public R signUp(Long activityId, String phone, @LoginUser UserEntity userEntity) {
        return R.ok(signUpService.signUp(userEntity.getId(),activityId,phone));
    }

    /**
     * 支付成功回调地址
     * @return
     */
    @RequestMapping("/wx/pay")
    @IgnoreAuth
    public String wxPay(@RequestBody String body){
        Map<String,String> result = wxPayService.handleWxNotice(body);
        String orderNo = result.get("out_trade_no");
        String totalFee = result.get("total_fee"); //单位 分
        //TODO 如果orderNo的订单状态是没有支付的  改变订单的支付状态  验证支付金额是否正确 保存在学习课程记录
        signUpService.updatePayStatus(orderNo,totalFee);
        //通知微信 已经收到通知
        return "<xml>\n" +
                "\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }
}
